#!/usr/bin/env python3

# Copyright (c) 2020-2021 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


import os
import pathlib
import subprocess
from .._util import Util
from .._workdir import WorkDirAddonBase
from .._vm import Vm
from ._z import VirtualUserWin10
from ._unattended import AnswerFile


class WorkDirAddon(WorkDirAddonBase):

    def __init__(self, parent):
        self._parent = parent

    @property
    def installation_iso_filepath(self):
        return os.path.join(self._parent._path, "install.iso")

    @property
    def virtio_win_iso_filepath(self):
        return os.path.join(self._parent._path, "virtio-win.iso")

    @property
    def unattend_usb_stick_filepath(self):
        return os.path.join(self._parent._path, "unattend_usb.img")

    @property
    def iso_op_dirpath(self):
        return os.path.join(self._parent._path, "iso.dir")

    @property
    def usb_stick_op_dirpath(self):
        return os.path.join(self._parent._path, "usb.dir")

    @property
    def tmp_file(self):
        return os.path.join(self._parent._path, "tmp.file")


class BuildUtil:

    @staticmethod
    def prepare(ts, workDirObj, srcMedia):
        # copy iso file, we don't need to modify it
        subprocess.check_call(["cp", srcMedia.get_iso_filepath(), workDirObj.installation_iso_filepath])

        # copy virtio-win.iso
        if "virtio" in ts.extra_drivers:
            subprocess.check_call(["cp", srcMedia.get_virtio_win_iso_filepath(), workDirObj.virtio_win_iso_filepath])

        # create an unattend virtual usb stick
        if True:
            Util.forceMakeEmptyDir(workDirObj.usb_stick_op_dirpath)
            loopFile, mntDir = Util.usbHddCreate(workDirObj.unattend_usb_stick_filepath, "32M", workDirObj.usb_stick_op_dirpath, bMountFs=True)
            try:
                answerFile = AnswerFile(ts)
                pathlib.Path(os.path.join(mntDir, answerFile.get_filename())).write_text(answerFile.get_content())
            finally:
                Util.usbHddUnMount(workDirObj.unattend_usb_stick_filepath, workDirObj.usb_stick_op_dirpath, loopFile, mntDir)

    @staticmethod
    def osInstall(ts, workDirObj, bDebug):
        # install
        vm = Vm(workDirObj)
        vm.set_record_file("install.mp4")
        vm.set_no_reboot(True)
        vm.use_cdrom(workDirObj.installation_iso_filepath, boot=True)
        vm.use_usb_stick(workDirObj.unattend_usb_stick_filepath)
        vm.start(show=bDebug)
        try:
            vuser = VirtualUserWin10("eng", vm)
            vuser.operate(vuser.BootFromCdrom())
            vm.wait_until_stop()
        except BaseException:
            vm.stop()
            raise

        # install
        vm = Vm(workDirObj)
        vm.set_record_file("install.mp4")
        vm.start(show=bDebug)
        try:
            vuser = VirtualUserWin10("eng", vm)
            vuser.operate(vuser.WaitInstallFinish())
            vm.shutdown()
            vm.wait_until_stop()
        except BaseException:
            vm.stop()
            raise

    @staticmethod
    def cleanup(ts, workDirObj):
        pass
